{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'channels_last'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "from keras.layers.core import Dense,Flatten\n",
    "from keras.layers.convolutional import Conv2D\n",
    "from keras.layers.pooling import MaxPooling2D\n",
    "from keras import backend as K\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "import math\n",
    "import tensorflow as tf\n",
    "K.image_data_format()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "导入数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-bd77ce8c80c9>:3: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From /home/sika0819/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From /home/sika0819/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting ./train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From /home/sika0819/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting ./train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /home/sika0819/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting ./t10k-images-idx3-ubyte.gz\n",
      "Extracting ./t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /home/sika0819/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = './'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "建立卷积神经网络"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "\n",
    "with tf.name_scope('reshape'):\n",
    "  x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "\n",
    "net = Conv2D(32, kernel_size=[5,5], strides=[1,1],activation='relu',\n",
    "                 padding='same',\n",
    "                input_shape=[28,28,1])(x_image)\n",
    "net = MaxPooling2D(pool_size=[2,2])(net)\n",
    "net = Conv2D(64, kernel_size=[5,5], strides=[1,1],activation='relu',\n",
    "                padding='same')(net)\n",
    "net = MaxPooling2D(pool_size=[2,2])(net)\n",
    "net = Flatten()(net)\n",
    "#激活函数为relu\n",
    "net = Dense(1000, activation='relu')(net)\n",
    "net = Dense(10,activation='softmax')(net)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义交叉商和带L2正则的损失函数防止过拟合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.objectives import categorical_crossentropy\n",
    "cross_entropy = tf.reduce_mean(categorical_crossentropy(y_, net))\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] )\n",
    "total_loss = cross_entropy + 7e-5*l2_loss"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一次喂入的数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "BATCH_SIZE=100"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义指数下降学习率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "LEARNING_RATE_BASE=0.1\n",
    "LEARNING_RATE_DECAY=0.99\n",
    "LEARNING_RATE_STEP=1\n",
    "global_step=tf.Variable(0,trainable=False)\n",
    "learning_rate=tf.train.exponential_decay(LEARNING_RATE_BASE,global_step,LEARNING_RATE_STEP,LEARNING_RATE_DECAY,staircase=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义一个step训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_step = tf.train.AdamOptimizer(learning_rate).minimize(total_loss,global_step)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义准确率计算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "correct_prediction = tf.equal(tf.argmax(net, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 0.241443, l2_loss: 1127.722656, total loss: 0.320383\n",
      "0.95\n",
      "step 200, entropy loss: 0.111856, l2_loss: 729.288391, total loss: 0.162907\n",
      "0.98\n",
      "step 300, entropy loss: 0.129266, l2_loss: 588.705566, total loss: 0.170475\n",
      "0.98\n",
      "step 400, entropy loss: 0.129955, l2_loss: 520.288513, total loss: 0.166375\n",
      "0.98\n",
      "step 500, entropy loss: 0.051004, l2_loss: 494.809387, total loss: 0.085641\n",
      "1.0\n",
      "step 600, entropy loss: 0.290328, l2_loss: 497.064117, total loss: 0.325123\n",
      "0.95\n",
      "step 700, entropy loss: 0.045232, l2_loss: 487.110016, total loss: 0.079330\n",
      "0.99\n",
      "step 800, entropy loss: 0.100981, l2_loss: 500.689575, total loss: 0.136029\n",
      "0.98\n",
      "step 900, entropy loss: 0.023740, l2_loss: 502.374939, total loss: 0.058906\n",
      "1.0\n",
      "step 1000, entropy loss: 0.097686, l2_loss: 506.682587, total loss: 0.133153\n",
      "0.97\n",
      "step 1100, entropy loss: 0.233339, l2_loss: 526.793091, total loss: 0.270215\n",
      "0.96\n",
      "step 1200, entropy loss: 0.105351, l2_loss: 530.976440, total loss: 0.142519\n",
      "0.97\n",
      "step 1300, entropy loss: 0.060149, l2_loss: 545.313965, total loss: 0.098321\n",
      "0.98\n",
      "step 1400, entropy loss: 0.153655, l2_loss: 548.568848, total loss: 0.192055\n",
      "0.98\n",
      "step 1500, entropy loss: 0.094825, l2_loss: 557.677002, total loss: 0.133863\n",
      "0.98\n",
      "step 1600, entropy loss: 0.029523, l2_loss: 588.032288, total loss: 0.070685\n",
      "1.0\n",
      "step 1700, entropy loss: 0.062239, l2_loss: 572.941956, total loss: 0.102345\n",
      "0.99\n",
      "step 1800, entropy loss: 0.102860, l2_loss: 583.640747, total loss: 0.143715\n",
      "0.98\n",
      "step 1900, entropy loss: 0.086126, l2_loss: 591.276672, total loss: 0.127516\n",
      "0.99\n",
      "step 2000, entropy loss: 0.147315, l2_loss: 590.964111, total loss: 0.188682\n",
      "0.99\n",
      "step 2100, entropy loss: 0.038735, l2_loss: 597.802368, total loss: 0.080581\n",
      "1.0\n",
      "step 2200, entropy loss: 0.117058, l2_loss: 597.854126, total loss: 0.158908\n",
      "0.97\n",
      "step 2300, entropy loss: 0.019044, l2_loss: 606.020325, total loss: 0.061466\n",
      "1.0\n",
      "step 2400, entropy loss: 0.180047, l2_loss: 599.677795, total loss: 0.222025\n",
      "0.97\n",
      "step 2500, entropy loss: 0.060785, l2_loss: 614.333801, total loss: 0.103788\n",
      "0.99\n",
      "step 2600, entropy loss: 0.082384, l2_loss: 614.878113, total loss: 0.125426\n",
      "0.97\n",
      "step 2700, entropy loss: 0.073551, l2_loss: 611.356934, total loss: 0.116346\n",
      "0.98\n",
      "step 2800, entropy loss: 0.121101, l2_loss: 622.242920, total loss: 0.164658\n",
      "0.98\n",
      "step 2900, entropy loss: 0.077785, l2_loss: 604.924805, total loss: 0.120129\n",
      "0.97\n",
      "step 3000, entropy loss: 0.038945, l2_loss: 605.551697, total loss: 0.081333\n",
      "0.98\n"
     ]
    }
   ],
   "source": [
    "with tf.Session() as sess:\n",
    "    init_op = tf.global_variables_initializer()\n",
    "    sess.run(init_op)\n",
    "    for i in range(3000):\n",
    "        batch_xs, batch_ys = mnist.train.next_batch(BATCH_SIZE)\n",
    "        learning_rate_val=sess.run(learning_rate)\n",
    "        global_step_val=sess.run(global_step)\n",
    "        lr = 0.01\n",
    "        _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr})\n",
    "  \n",
    "        if (i+1) % 100 == 0:\n",
    "            print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (i+1, loss, l2_loss_value, total_loss_value))\n",
    "            # Test trained model\n",
    "            print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以看到卷积神经网络过程中，某次训练准确率较高，下一次准确率却明显下降，推测可能是发生了过拟合，用L2正则进行了调整。准确率震荡比较明显，可能是以凯撒学习率定的太大了。最后经过训练后卷积神经网络准确率稳定在了0.98左右,损失也性对较小"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
